package name.suray.andrey;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class MyCompiler {
	
	public MyCompiler(){
		
	}

	public Class<?> compile(String className){
		
		System.out.println("In MtCompiler.compile()...");
		
//		String fileToCompile = "D:\\" + className + ".java";
//		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
//		int compilationResult =	compiler.run(null, null, null, fileToCompile);
//		if(compilationResult == 0){
//			System.out.println("Compilation is successful");
//		}else{
//			System.out.println("Compilation Failed");
//		}
		
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
		Iterable<? extends JavaFileObject> compilationUnits = 
			fileManager.getJavaFileObjectsFromStrings(Arrays.asList("src\\name\\suray\\andrey\\" + className + ".java"));
		Iterable<String> options = Arrays.asList("-d","bin");
		JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options ,null, compilationUnits);
		boolean compilationResult = task.call();
		
		if(compilationResult){
			System.out.println("Compilation is successful");
		}else{
			System.out.println("Compilation Failed");
		}
		
		Class<?> c = null;
		try {
			
			fileManager.close();
			File file = new File("\\bin");
			URL url = file.toURI().toURL(); 
			URL[] classUrls = new URL[] { url };
			URLClassLoader ucl = new URLClassLoader(classUrls,this.getClass().getClassLoader());
			c = ucl.loadClass("name.suray.andrey." + className);
			
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return c;
		
	}//end of compile
}//end of class MyCompiler
